package account

import (
	"ginweb/common"
	"github.com/gin-gonic/gin"
	"net/http"
)

type Account struct {
	Id         int    `json:"id"`
	Uname      string `json:"uname"`
	Passwd     string `json:"passwd"`
	PasswdSalt string `json:"passwd_salt"`
	Status     int    `json:"status"`
	LastLogin  int    `json:"last_login"`
	CreateTime int    `json:"create_time"`
}

func (Account) TableName() string {
	return "account"
}

func Login(c *gin.Context) {

	if common.CheckLogin(c) {
		c.Redirect(302, "/dashboard")
	}

	c.HTML(http.StatusOK, "login.html", gin.H{
		"title": "Main website",
	})

}

func LoginIn(c *gin.Context) {

	account := Account{}
	c.ShouldBind(&account)

	//log.Println("%s--%s", account.Uname, account.Passwd)

	if account.Uname == "" || account.Passwd == "" {
		common.ReturnMsg(200, 0, "参数错误", c)
		return
	}

	db := common.InitDB()
	defer db.Close()

	var info []Account

	db.Where("uname=?", account.Uname).First(&info)

	if len(info) == 0 {
		common.ReturnMsg(200, 0, "登录失败", c)
		return
	}

	//log.Println("%s", setMd5("123456qwer1234"))

	//校验密码
	if common.SetMd5(account.Passwd+info[0].PasswdSalt) != info[0].Passwd {
		common.ReturnMsg(200, 0, "登录失败", c)
		return
	}

	//保存登录信息到redis
	session := common.LoginSession{info[0].Id, info[0].Uname, info[0].Status, info[0].LastLogin}
	if !common.SetLogin(&session) {
		common.ReturnMsg(200, 0, "登录失败", c)
		return
	}

	common.SetCookie(c, info[0].Id)

	common.ReturnMsg(200, 1, "登录成功", c)

	//m := md5.New()
	//m.Write([]byte("123456qwer1234"))

	//log.Println("%s", hex.EncodeToString(m.Sum(nil)))
	//md5.Sum([]byte("123456"))

	//log.Println("%d", len(info))
	//log.Println("%v", &info)

	//log.Println("%v", &info)

	/*



		db, err := sql.Open("mysql", "root:@123456(127.0.0.1:3306)/jose-web?parseTime=true")
		if err != nil {
			log.Fatalln(err)
		}
		defer db.Close()

		db.SetMaxIdleConns(20)
		db.SetMaxOpenConns(20)

		if err := db.Ping(); err != nil {
			log.Fatalln(err)
		}

		accountInfo := Account{}

		err2 := db.QueryRow("select * from account where uname=?", account.Uname).Scan(&accountInfo.Id, &accountInfo.Uname, &accountInfo.Passwd, &accountInfo.PasswdSalt)

		if err2 != nil {
			log.Println("%v", &accountInfo)
			return
		}



	*/

}

func LoginOut(c *gin.Context) {
	common.LoginOut(c)
	common.ReturnMsg(200, 1, "", c)
}
